﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using GalaSoft.MvvmLight.Command;
using Microsoft.Phone.Controls;

namespace BingleMaps.Controls
{
	public class SearchBox : AutoCompleteBox
	{
		#region Private Mambers

		private TextBox _textBox;
		private Selector _selector;

		#endregion


		#region Events

		public event RoutedEventHandler Search;

		#endregion


		#region Event Handling

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			CommandPopulateComplete = new RelayCommand(PopulateComplete);
			_textBox = GetTemplateChild("Text") as TextBox;
			_selector = GetTemplateChild("Selector") as Selector;
			if (_selector == null)
			{
				return;
			}
			_selector.RenderTransform = new TranslateTransform { Y = PopupVerticalOffset };
		}

		protected override void OnGotFocus(RoutedEventArgs e)
		{
			base.OnGotFocus(e);
			if (_textBox == null)
			{
				return;
			}
			_textBox.Focus();
			_textBox.SelectAll();
		}

		protected override void OnKeyDown(KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				e.Handled = true;
				if (Search != null)
				{
					Search(this, e);
				}
			}
			else
			{
				base.OnKeyDown(e);
			}
		}

		private static void OnPopupVerticalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var searchBox = d as SearchBox;
			if (searchBox == null || searchBox._selector == null)
			{
				return;
			}
			searchBox._selector.RenderTransform = new TranslateTransform { Y = (double)e.NewValue };
		}

		#endregion


		#region Dependency Properties

		public double PopupVerticalOffset
		{
			get { return (double)GetValue(PopupVerticalOffsetProperty); }
			set { SetValue(PopupVerticalOffsetProperty, value); }
		}

		public static readonly DependencyProperty PopupVerticalOffsetProperty = DependencyProperty.Register(
			"PopupVerticalOffset",
			typeof(double),
			typeof(SearchBox),
			new PropertyMetadata(OnPopupVerticalOffsetChanged));

		#endregion


		#region Commands

		public ICommand SearchCommand
		{
			get { return (ICommand)GetValue(SearchCommandProperty); }
			set { SetValue(SearchCommandProperty, value); }
		}

		public static readonly DependencyProperty SearchCommandProperty = DependencyProperty.Register(
			"SearchCommand",
			typeof(ICommand),
			typeof(SearchBox),
			null);

		public ICommand CommandPopulateComplete
		{
			get { return (ICommand)GetValue(CommandPopulateCompleteProperty); }
			set { SetValue(CommandPopulateCompleteProperty, value); }
		}

		public static readonly DependencyProperty CommandPopulateCompleteProperty = DependencyProperty.Register(
			"CommandPopulateComplete",
			typeof(ICommand),
			typeof(SearchBox),
			null);

		#endregion
	}
}
